import {defineStore} from 'pinia'

let progressStop = import.meta.env.VITE_PROGRESS_STOP
let stopTime = import.meta.env.VITE_STOP_TIME

export const useProgressStore = defineStore({
  id: 'progress',
  state: () => ({
    // 当前进度
    percentage: 0,
    // 上一帧动画的时间
    lastTime: 0,
    // 假加载停止位置
    progressStop,
    // 假加载用时
    stopTime,
    // 单步速度
    speed: progressStop / stopTime,
    // 动画帧id
    animationId: 0
  }),
  actions: {
    // 开启进度条
    progressStart(): void {
      if (!this.lastTime) {
        this.lastTime = new Date().getTime()
        this.animationId = requestAnimationFrame(this.progressStart)
        return
      }
      // 当前时间
      let thisTime = new Date().getTime()
      // 时间区间
      let divideTime = thisTime - this.lastTime
      this.lastTime = thisTime
      // 进度条行进
      let tag = this.percentage + divideTime * this.speed
      // 超过指定位置，结束
      if (tag >= this.progressStop) return
      this.percentage = tag
      this.animationId = requestAnimationFrame(this.progressStart)
    },

    // 结束进度条
    progressEnd(): void {
      cancelAnimationFrame(this.animationId)
      this.percentage = 100

      // 定时让进度条消失
      setTimeout(() => {
        this.lastTime = 0
        this.percentage = 0
      }, 600)
    }
  }
})